package com.dms.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.order.dto.OrderDTO;
import com.dms.modules.order.dto.OrderItemDTO;
import com.dms.modules.order.dto.RefundAuditDTO;
import com.dms.modules.order.dto.OrderSubmitDTO;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.entity.OrderItem;
import com.dms.modules.order.enums.OrderStatus;
import com.dms.modules.order.mapper.OrderMapper;
import com.dms.modules.order.service.OrderItemService;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.order.utils.OrderNoGenerator;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dms.modules.order.event.OrderEvent;
import org.springframework.context.ApplicationEventPublisher;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Objects;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dms.modules.cart.entity.CartItem;
import com.dms.modules.cart.service.CartService;
import com.dms.modules.order.vo.OrderDetailVO;
import com.dms.modules.order.vo.OrderVO;
import com.dms.modules.user.entity.UserAddress;
import com.dms.modules.user.service.UserAddressService;
import com.dms.modules.order.entity.Coupon;
import com.dms.modules.order.entity.UserCoupon;
import org.springframework.scheduling.annotation.Scheduled;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.dms.modules.message.service.BusinessMessageService;
import com.dms.modules.message.dto.BusinessMessageDTO;
import com.dms.modules.message.enums.BusinessMessageType;
import lombok.extern.slf4j.Slf4j;
import com.google.gson.Gson;
import com.dms.modules.order.service.UserCouponService;
import com.dms.modules.product.entity.ProductSku;
import com.dms.modules.product.service.ProductSkuService;
import com.dms.modules.order.entity.OrderRefund;
import com.dms.modules.order.service.OrderRefundService;
import com.dms.modules.user.vo.UserInfoVO;
import com.dms.modules.user.service.UserCenterService;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemService orderItemService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private OrderNoGenerator orderNoGenerator;
    
    @Autowired
    private UserAddressService userAddressService;
    
    @Autowired
    private CartService cartService;

    @Autowired
    private UserCouponService userCouponService;

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private BusinessMessageService businessMessageService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private UserCenterService userCenterService;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public boolean checkStock(OrderItemDTO orderItemDTO) {
        // 检查商品是否存在
        Product product = productService.getById(orderItemDTO.getProductId());
        if (product == null || product.getStatus() != 1) {
            return false;
        }
        
        // 检查SKU是否存在
        if (orderItemDTO.getSkuId() != null) {
            ProductSku sku = productSkuService.getById(orderItemDTO.getSkuId());
            if (sku == null || sku.getStatus() != 1 || !sku.getProductId().equals(product.getId())) {
                return false;
            }
            
            // 检查库存是否充足
            if (sku.getStock() < orderItemDTO.getQuantity()) {
                return false;
            }
        } else {
            // 检查商品库存是否充足
            if (product.getStock() < orderItemDTO.getQuantity()) {
                return false;
            }
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Long> submitOrder(Long userId, OrderSubmitDTO submitDTO) {
        // 1. 校验收货地址
        UserAddress address = userAddressService.getAddressById(submitDTO.getAddressId());
        if (address == null || !address.getUserId().equals(userId)) {
            throw new BusinessException("收货地址不存在或不属于当前用户");
        }
        List<Long> orderIds = new ArrayList<>();
        // 2. 购物车下单（多商家拆单）
        if (Boolean.TRUE.equals(submitDTO.getUseCart())) {
            if (submitDTO.getCartItemIds() == null || submitDTO.getCartItemIds().isEmpty()) {
                throw new BusinessException("请选择要购买的商品");
            }
            List<CartItem> cartItems = cartService.listByIds(submitDTO.getCartItemIds());
            if (cartItems.isEmpty()) {
                throw new BusinessException("购物车商品不存在");
            }
            for (CartItem cartItem : cartItems) {
                if (!cartItem.getUserId().equals(userId)) {
                    throw new BusinessException("购物车商品不属于当前用户");
                }
            }
            Map<Long, List<CartItem>> cartItemsByMerchant = cartItems.stream()
                .collect(Collectors.groupingBy(CartItem::getMerchantId));
            for (Map.Entry<Long, List<CartItem>> entry : cartItemsByMerchant.entrySet()) {
                Long merchantId = entry.getKey();
                List<CartItem> merchantCartItems = entry.getValue();
                Order order = new Order();
                order.setUserId(userId);
                order.setMerchantId(merchantId);
                order.setOrderNo(orderNoGenerator.generate());
                order.setStatus(OrderStatus.PENDING_PAYMENT.getCode());
                // 地址快照
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, String> addressMap = new HashMap<>();
                    addressMap.put("receiverName", address.getReceiverName());
                    addressMap.put("receiverPhone", address.getReceiverPhone());
                    addressMap.put("province", address.getProvince());
                    addressMap.put("city", address.getCity());
                    addressMap.put("district", address.getDistrict());
                    addressMap.put("detailAddress", address.getDetailAddress());
                    String addressSnapshot = objectMapper.writeValueAsString(addressMap);
                    order.setAddressSnapshot(addressSnapshot);
                } catch (Exception e) {
                    log.error("序列化地址信息失败", e);
                    throw new BusinessException("创建订单失败：地址信息处理异常");
                }
                order.setRemark(submitDTO.getRemark());
                // 订单项
                List<OrderItem> orderItems = new ArrayList<>();
                BigDecimal totalAmount = BigDecimal.ZERO;
                for (CartItem cartItem : merchantCartItems) {
                    Product product = productService.getById(cartItem.getProductId());
                    if (product == null) {
                        throw new BusinessException("商品不存在: " + cartItem.getProductName());
                    }
                    if (product.getStock() < cartItem.getQuantity()) {
                        throw new BusinessException("商品库存不足: " + cartItem.getProductName());
                    }
                    OrderItem orderItem = new OrderItem();
                    orderItem.setProductId(cartItem.getProductId());
                    orderItem.setMerchantId(product.getMerchantId());
                    orderItem.setSkuId(cartItem.getSkuId() != null ? cartItem.getSkuId() : 0L);
                    orderItem.setQuantity(cartItem.getQuantity());
                    orderItem.setPrice(cartItem.getPrice());
                    orderItem.setTotalAmount(cartItem.getTotalPrice());
                    orderItem.setProductName(cartItem.getProductName());
                    orderItem.setProductImg(cartItem.getProductImg());
                    // 处理规格信息，确保是JSON格式
                    try {
                        if (cartItem.getSpecInfo() != null) {
                            // 验证是否已经是JSON格式
                            try {
                                new ObjectMapper().readTree(cartItem.getSpecInfo());
                                orderItem.setSpecInfo(cartItem.getSpecInfo());
                            } catch (Exception e) {
                                // 如果不是JSON格式，转换为JSON
                                Map<String, String> specMap = new HashMap<>();
                                specMap.put("规格", cartItem.getSpecInfo());
                                orderItem.setSpecInfo(new ObjectMapper().writeValueAsString(specMap));
                            }
                        } else {
                            // 如果规格信息为空，创建默认JSON
                            Map<String, String> defaultSpec = new HashMap<>();
                            defaultSpec.put("规格", "默认规格");
                            orderItem.setSpecInfo(new ObjectMapper().writeValueAsString(defaultSpec));
                        }
                    } catch (Exception e) {
                        log.error("处理规格信息失败", e);
                        throw new BusinessException("创建订单失败：规格信息处理异常");
                    }
                    try {
                        ObjectMapper objectMapper = new ObjectMapper();
                        Map<String, Object> productMap = new HashMap<>();
                        productMap.put("productId", cartItem.getProductId());
                        productMap.put("productName", cartItem.getProductName());
                        productMap.put("skuId", cartItem.getSkuId());
                        productMap.put("price", cartItem.getPrice().toString());
                        productMap.put("specInfo", orderItem.getSpecInfo());
                        String productSnapshot = objectMapper.writeValueAsString(productMap);
                        orderItem.setProductSnapshot(productSnapshot);
                    } catch (Exception e) {
                        log.error("序列化商品信息失败", e);
                        throw new BusinessException("创建订单失败：商品信息处理异常");
                    }
                    orderItems.add(orderItem);
                    totalAmount = totalAmount.add(cartItem.getTotalPrice());
                }
                order.setTotalAmount(totalAmount);
                order.setPayAmount(totalAmount);
                // 运费
                BigDecimal freightAmount = BigDecimal.valueOf(10);
                order.setFreightAmount(freightAmount);
                order.setPayAmount(order.getPayAmount().add(freightAmount));
                order.setCreateTime(LocalDateTime.now());
                order.setUpdateTime(LocalDateTime.now());
                boolean saved = save(order);
                if (!saved) {
                    throw new BusinessException("创建订单失败");
                }
                for (OrderItem item : orderItems) {
                    item.setOrderId(order.getId());
                    item.setCreateTime(LocalDateTime.now());
                }
                boolean itemsSaved = orderItemService.saveBatch(orderItems);
                if (!itemsSaved) {
                    throw new BusinessException("创建订单项失败");
                }
                // 存储购物车项ID，用于支付成功后删除
                if (submitDTO.getCartItemIds() != null && !submitDTO.getCartItemIds().isEmpty()) {
                    String cartItemIds = String.join(",", submitDTO.getCartItemIds().stream()
                        .map(String::valueOf)
                        .collect(Collectors.toList()));
                    order.setCartItemIds(cartItemIds);
                    updateById(order);
                }
                orderIds.add(order.getId());
            }
            return orderIds;
        }
        // 直接购买
        else if (submitDTO.getItem() != null) {
            OrderItemDTO itemDTO = submitDTO.getItem();
            Product product = productService.getById(itemDTO.getProductId());
            if (product == null) {
                throw new BusinessException("商品不存在");
            }
            if (!checkStock(itemDTO)) {
                throw new BusinessException("商品库存不足");
            }

            Order order = new Order();
            order.setUserId(userId);
            order.setMerchantId(product.getMerchantId());
            order.setOrderNo(orderNoGenerator.generate());
            order.setStatus(OrderStatus.PENDING_PAYMENT.getCode());
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, String> addressMap = new HashMap<>();
                addressMap.put("receiverName", address.getReceiverName());
                addressMap.put("receiverPhone", address.getReceiverPhone());
                addressMap.put("province", address.getProvince());
                addressMap.put("city", address.getCity());
                addressMap.put("district", address.getDistrict());
                addressMap.put("detailAddress", address.getDetailAddress());
                String addressSnapshot = objectMapper.writeValueAsString(addressMap);
                order.setAddressSnapshot(addressSnapshot);
            } catch (Exception e) {
                log.error("序列化地址信息失败", e);
                throw new BusinessException("创建订单失败：地址信息处理异常");
            }
            order.setRemark(submitDTO.getRemark());
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(product.getId());
            orderItem.setMerchantId(product.getMerchantId());
            orderItem.setSkuId(itemDTO.getSkuId() != null ? itemDTO.getSkuId() : 0L);
            orderItem.setQuantity(itemDTO.getQuantity());
            orderItem.setPrice(product.getPrice());
            orderItem.setTotalAmount(product.getPrice().multiply(new BigDecimal(itemDTO.getQuantity())));
            orderItem.setProductName(product.getName());
            orderItem.setProductImg(product.getMainImage());
            // 处理规格信息，确保是JSON格式
            try {
                if (itemDTO.getSpecInfo() != null) {
                    // 验证是否已经是JSON格式
                    try {
                        new ObjectMapper().readTree(itemDTO.getSpecInfo());
                        orderItem.setSpecInfo(itemDTO.getSpecInfo());
                    } catch (Exception e) {
                        // 如果不是JSON格式，转换为JSON
                        Map<String, String> specMap = new HashMap<>();
                        specMap.put("规格", itemDTO.getSpecInfo());
                        orderItem.setSpecInfo(new ObjectMapper().writeValueAsString(specMap));
                    }
                } else {
                    // 如果规格信息为空，创建默认JSON
                    Map<String, String> defaultSpec = new HashMap<>();
                    defaultSpec.put("规格", "默认规格");
                    orderItem.setSpecInfo(new ObjectMapper().writeValueAsString(defaultSpec));
                }
            } catch (Exception e) {
                log.error("处理规格信息失败", e);
                throw new BusinessException("创建订单失败：规格信息处理异常");
            }
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("productId", product.getId());
                productMap.put("productName", product.getName());
                productMap.put("skuId", itemDTO.getSkuId());
                productMap.put("price", product.getPrice().toString());
                productMap.put("specInfo", orderItem.getSpecInfo());
                String productSnapshot = objectMapper.writeValueAsString(productMap);
                orderItem.setProductSnapshot(productSnapshot);
            } catch (Exception e) {
                log.error("序列化商品信息失败", e);
                throw new BusinessException("创建订单失败：商品信息处理异常");
            }
            List<OrderItem> orderItems = new ArrayList<>();
            orderItems.add(orderItem);
            BigDecimal totalAmount = orderItem.getTotalAmount();
            order.setTotalAmount(totalAmount);
            order.setPayAmount(totalAmount);
            BigDecimal freightAmount = BigDecimal.valueOf(10);
            order.setFreightAmount(freightAmount);
            order.setPayAmount(order.getPayAmount().add(freightAmount));
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            boolean saved = save(order);
            if (!saved) {
                throw new BusinessException("创建订单失败");
            }
            for (OrderItem item : orderItems) {
                item.setOrderId(order.getId());
                item.setCreateTime(LocalDateTime.now());
            }
            boolean itemsSaved = orderItemService.saveBatch(orderItems);
            if (!itemsSaved) {
                throw new BusinessException("创建订单项失败");
            }
            orderIds.add(order.getId());
            return orderIds;
        } else {
            throw new BusinessException("订单中没有商品");
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long userId, Long orderId, String cancelReason) {
        log.info("取消订单，用户ID: {}, 订单ID: {}, 原因: {}", userId, orderId, cancelReason);
        
        // 1. 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 2. 验证订单所属用户
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作此订单");
        }
        
        // 3. 验证订单状态，只有待付款状态可以取消
        if (order.getStatus() != OrderStatus.PENDING_PAYMENT.getCode()) {
            throw new BusinessException("当前订单状态不能取消");
        }
        
        // 4. 设置取消信息
        order.setStatus(OrderStatus.CANCELLED.getCode());
        order.setCancelReason(cancelReason);
        order.setUpdateTime(LocalDateTime.now());
        
        // 5. 更新订单
        boolean updated = updateById(order);
        
        // 6. 如果取消成功，归还库存
        if (updated) {
            try {
                // 获取订单项
                List<OrderItem> orderItems = orderItemService.list(
                    new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, orderId)
                );
                
                // 归还库存
                for (OrderItem item : orderItems) {
                    Product product = productService.getById(item.getProductId());
                    if (product != null) {
                        // 增加库存
                        product.setStock(product.getStock() + item.getQuantity());
                        productService.updateById(product);
                        log.info("商品库存已归还，商品ID: {}, 数量: {}", item.getProductId(), item.getQuantity());
                    } else {
                        log.warn("商品不存在，无法归还库存，商品ID: {}", item.getProductId());
                    }
                }
            } catch (Exception e) {
                log.error("归还库存失败，订单ID: {}", orderId, e);
                // 这里不抛出异常，不影响取消订单的主流程
            }
            
            log.info("订单取消成功，订单ID: {}", orderId);
        } else {
            log.error("订单取消失败，订单ID: {}", orderId);
        }
        
        // 发送消息通知
        try {
            BusinessMessageDTO messageDTO = BusinessMessageDTO.builder()
                .type(getMessageType(OrderStatus.CANCELLED.getCode()))
                .businessId(orderId)
                .userId(userId)
                .params(buildMessageParams(order))
                .build();
            
            businessMessageService.sendBusinessMessage(messageDTO);
        } catch (Exception e) {
            log.error("发送订单状态变更消息失败: orderId={}, status={}, error={}", 
                orderId, OrderStatus.CANCELLED.getCode(), e.getMessage(), e);
        }
        
        return updated;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long userId, Long orderId, String paymentMethod, String paymentNo) {
        log.info("支付订单，用户ID: {}, 订单ID: {}, 支付方式: {}, 支付流水号: {}", 
                userId, orderId, paymentMethod, paymentNo);
        
        // 1. 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 2. 验证订单所属用户
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作此订单");
        }
        
        // 3. 验证订单状态，只有待付款状态可以支付
        if (order.getStatus() != OrderStatus.PENDING_PAYMENT.getCode()) {
            throw new BusinessException("当前订单状态不能支付");
        }
        
        try {
            // 4. 扣减库存
            List<OrderItem> orderItems = orderItemService.list(
                new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderId, orderId)
            );
            
            for (OrderItem item : orderItems) {
                // 检查是否是SKU商品
                if (item.getSkuId() != null && item.getSkuId() > 0) {
                    ProductSku sku = productSkuService.getById(item.getSkuId());
                    if (sku == null) {
                        throw new BusinessException("商品SKU不存在");
                    }
                    if (sku.getStock() < item.getQuantity()) {
                        throw new BusinessException("商品SKU库存不足");
                    }
                    // 扣减SKU库存
                    sku.setStock(sku.getStock() - item.getQuantity());
                    if (!productSkuService.updateById(sku)) {
                        throw new BusinessException("扣减SKU库存失败");
                    }
                } else {
                    // 扣减商品总库存
                Product product = productService.getById(item.getProductId());
                if (product == null) {
                        throw new BusinessException("商品不存在");
                }
                if (product.getStock() < item.getQuantity()) {
                        throw new BusinessException("商品库存不足");
                }
                product.setStock(product.getStock() - item.getQuantity());
                    if (!productService.updateById(product)) {
                        throw new BusinessException("扣减商品库存失败");
                    }
                }
            }
            
            // 5. 清理购物车
            if (order.getCartItemIds() != null && !order.getCartItemIds().isEmpty()) {
                String[] cartItemIdArray = order.getCartItemIds().split(",");
                List<Long> cartItemIds = Arrays.stream(cartItemIdArray)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
                
                if (!cartService.removeByIds(cartItemIds)) {
                    log.error("清理购物车失败，订单ID: {}, 购物车项: {}", orderId, cartItemIds);
                }
            }
            
            // 6. 设置支付信息
            order.setStatus(OrderStatus.PENDING_SHIPMENT.getCode());
            order.setPaymentMethod(paymentMethod);
            order.setPaymentNo(paymentNo);
            order.setPaymentTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            
            // 7. 更新订单
            boolean updated = updateById(order);
            
            if (updated) {
                log.info("订单支付成功，订单ID: {}", orderId);
                
                // 8. 发送消息通知
        try {
            BusinessMessageDTO messageDTO = BusinessMessageDTO.builder()
                        .type(getMessageType(OrderStatus.PENDING_SHIPMENT.getCode()))
                .businessId(orderId)
                .userId(userId)
                .params(buildMessageParams(order))
                .build();
            
            businessMessageService.sendBusinessMessage(messageDTO);
        } catch (Exception e) {
            log.error("发送订单状态变更消息失败: orderId={}, status={}, error={}", 
                        orderId, OrderStatus.PENDING_SHIPMENT.getCode(), e.getMessage(), e);
                }
            } else {
                log.error("订单支付失败，订单ID: {}", orderId);
        }
        
        return updated;
        } catch (Exception e) {
            log.error("订单支付处理失败", e);
            throw new BusinessException("支付失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReceipt(Long userId, Long orderId) {
        log.info("确认收货，用户ID: {}, 订单ID: {}", userId, orderId);
        
        // 1. 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 2. 验证订单所属用户
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作此订单");
        }
        
        // 3. 验证订单状态，只有待收货状态可以确认收货
        if (order.getStatus() != OrderStatus.PENDING_RECEIPT.getCode()) {
            throw new BusinessException("当前订单状态不能确认收货");
        }
        
        // 4. 设置收货信息
        order.setStatus(OrderStatus.COMPLETED.getCode());
        order.setReceiveTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        // 5. 更新订单
        boolean updated = updateById(order);
        
        if (updated) {
            log.info("订单确认收货成功，订单ID: {}", orderId);
        } else {
            log.error("订单确认收货失败，订单ID: {}", orderId);
        }
        
        // 发送消息通知
        try {
            BusinessMessageDTO messageDTO = BusinessMessageDTO.builder()
                .type(getMessageType(OrderStatus.COMPLETED.getCode()))
                .businessId(orderId)
                .userId(userId)
                .params(buildMessageParams(order))
                .build();
            
            businessMessageService.sendBusinessMessage(messageDTO);
        } catch (Exception e) {
            log.error("发送订单状态变更消息失败: orderId={}, status={}, error={}", 
                orderId, OrderStatus.COMPLETED.getCode(), e.getMessage(), e);
        }
        
        return updated;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder(Long userId, Long orderId) {
        log.info("删除订单，用户ID: {}, 订单ID: {}", userId, orderId);
        
        // 1. 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 2. 验证订单所属用户
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作此订单");
        }
        
        // 3. 验证订单状态，只有已完成或已取消的订单可以删除
        if (order.getStatus() != OrderStatus.COMPLETED.getCode() && 
            order.getStatus() != OrderStatus.CANCELLED.getCode()) {
            throw new BusinessException("当前订单状态不能删除");
        }
        
        // 4. 逻辑删除订单（假设Order有deleted字段，如果没有则需要修改）
        order.setUpdateTime(LocalDateTime.now());
        // 如果Order实体有逻辑删除字段，设置该字段
        // order.setDeleted(1);
        boolean updated = updateById(order);
        
        if (updated) {
            log.info("订单删除成功，订单ID: {}", orderId);
        } else {
            log.error("订单删除失败，订单ID: {}", orderId);
        }
        
        return updated;
    }
    
    @Override
    public OrderDetailVO getOrderDetail(Long userId, Long orderId) {
        Order order = getById(orderId);
        if (order == null) {
            return null;
        }

        OrderDetailVO detailVO = new OrderDetailVO();
        BeanUtils.copyProperties(order, detailVO);
        
        // 设置订单状态文本
        detailVO.setStatusText(getOrderStatusText(order.getStatus()));
        
        // 获取用户信息
        try {
            UserInfoVO userInfo = userCenterService.getUserInfo(order.getUserId());
            if (userInfo != null) {
                detailVO.setUserName(userInfo.getNickname());
                detailVO.setUserPhone(userInfo.getPhone());
            }
        } catch (Exception e) {
            log.warn("获取用户信息失败: userId={}", order.getUserId(), e);
        }
        
        // 解析收货地址快照
        try {
            if (order.getAddressSnapshot() != null) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> addressMap = mapper.readValue(order.getAddressSnapshot(), Map.class);
                detailVO.setReceiverName(addressMap.get("receiverName"));
                detailVO.setReceiverPhone(addressMap.get("receiverPhone"));
                detailVO.setReceiverAddress(String.format("%s %s %s", 
                    addressMap.get("province"), 
                    addressMap.get("city"), 
                    addressMap.get("district")));
                detailVO.setReceiverDetailAddress(addressMap.get("detailAddress"));
            }
        } catch (Exception e) {
            log.warn("解析收货地址快照失败: orderId={}", orderId, e);
        }
        
        // 获取订单项
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId)
        );
        detailVO.setOrderItems(orderItems);
        
        // 计算商品总数
        int totalQuantity = orderItems.stream()
            .mapToInt(OrderItem::getQuantity)
            .sum();
        detailVO.setTotalQuantity(totalQuantity);
        
        // 设置按钮状态
        detailVO.setCanPay(order.getStatus() == OrderStatus.PENDING_PAYMENT.getCode());
        detailVO.setCanCancel(order.getStatus() == OrderStatus.PENDING_PAYMENT.getCode());
        detailVO.setCanConfirm(order.getStatus() == OrderStatus.PENDING_RECEIPT.getCode());
        detailVO.setCanRefund(order.getStatus() == OrderStatus.COMPLETED.getCode());
        
        return detailVO;
    }
    
    @Override
    public IPage<OrderVO> getUserOrders(Page<Order> page, Long userId, Integer status) {
        log.info("获取用户订单列表，用户ID: {}, 状态: {}", userId, status);
        
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        if (status != null) {
            queryWrapper.eq(Order::getStatus, status);
        }
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        // 查询订单分页数据
        IPage<Order> orderPage = page(page, queryWrapper);
        
        // 转换为OrderVO
        IPage<OrderVO> orderVOPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            
            // 设置订单状态文本
            switch (order.getStatus()) {
                case 0:
                    orderVO.setStatusText("待付款");
                    break;
                case 1:
                    orderVO.setStatusText("待发货");
                    break;
                case 2:
                    orderVO.setStatusText("待收货");
                    break;
                case 3:
                    orderVO.setStatusText("已完成");
                    break;
                case 4:
                    orderVO.setStatusText("已取消");
                    break;
                default:
                    orderVO.setStatusText("未知状态");
            }
            
            // 设置按钮状态
            orderVO.setCanPay(order.getStatus() == OrderStatus.PENDING_PAYMENT.getCode());
            orderVO.setCanCancel(order.getStatus() == OrderStatus.PENDING_PAYMENT.getCode());
            orderVO.setCanConfirm(order.getStatus() == OrderStatus.PENDING_RECEIPT.getCode());
            orderVO.setCanRefund(order.getStatus() == OrderStatus.COMPLETED.getCode());
            
            // 获取订单项
            List<OrderItem> orderItems = orderItemService.list(
                new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderId, order.getId())
            );
            orderVO.setOrderItems(orderItems);
            
            // 计算商品总数
            int totalQuantity = 0;
            for (OrderItem item : orderItems) {
                totalQuantity += item.getQuantity();
            }
            orderVO.setTotalQuantity(totalQuantity);
            
            // 设置主商品图片
            if (!orderItems.isEmpty()) {
                orderVO.setMainProductImg(orderItems.get(0).getProductImg());
            }
            
            return orderVO;
        }).collect(Collectors.toList());
        
        orderVOPage.setRecords(orderVOList);
        return orderVOPage;
    }
    
    @Override
    public Integer getUnpaidCount(Long userId) {
        // 查询待付款订单数量
        long count = count(
            new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(Order::getStatus, OrderStatus.PENDING_PAYMENT.getCode())
        );
        return (int) count;
    }
    
    @Override
    public Integer getUnshippedCount(Long userId) {
        // 查询待发货订单数量
        long count = count(
            new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(Order::getStatus, OrderStatus.PENDING_SHIPMENT.getCode())
        );
        return (int) count;
    }
    
    @Override
    public Integer getUnreceivedCount(Long userId) {
        // 查询待收货订单数量
        long count = count(
            new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .eq(Order::getStatus, OrderStatus.PENDING_RECEIPT.getCode())
        );
        return (int) count;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long applyRefund(Long userId, Long orderId, String reason) {
        log.info("申请退款，用户ID: {}, 订单ID: {}, 原因: {}", userId, orderId, reason);
        // 1. 检查订单是否存在
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        // 2. 验证订单所属用户
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作此订单");
        }
        // 3. 验证订单状态，只有待发货、待收货、已完成的订单可以申请退款
        if (order.getStatus() != OrderStatus.PENDING_SHIPMENT.getCode() && 
            order.getStatus() != OrderStatus.PENDING_RECEIPT.getCode() && 
            order.getStatus() != OrderStatus.COMPLETED.getCode()) {
            throw new BusinessException("当前订单状态不能申请退款");
        }
        // 4. 创建退款申请
        try {
            OrderRefund refund = new OrderRefund();
            refund.setOrderId(orderId);
            refund.setUserId(userId);
            refund.setRefundNo(generateRefundNo());
            refund.setRefundAmount(order.getPayAmount());
            refund.setRefundReason(reason);
            refund.setRefundType(0); // 仅退款
            refund.setStatus(0); // 申请中
            refund.setCreateTime(LocalDateTime.now());
            refund.setUpdateTime(LocalDateTime.now());
            orderRefundService.save(refund);
            // 更新订单状态为退款中（如有需要）
            order.setUpdateTime(LocalDateTime.now());
            updateById(order);
            log.info("退款申请成功，订单ID: {}, 退款单号: {}", orderId, refund.getRefundNo());
            return refund.getId();
        } catch (Exception e) {
            log.error("退款申请失败，订单ID: {}", orderId, e);
            throw new BusinessException("退款申请失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成退款单号
     */
    private String generateRefundNo() {
        return "RF" + System.currentTimeMillis();
    }
    
    /**
     * 查询退款状态（简单实现）
     * 在实际项目中，应该从数据库中查询退款记录
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return 退款状态（0-申请中，1-退款成功，2-退款失败）
     */
    public Integer getRefundStatus(Long userId, Long orderId) {
        // 这里简化处理，直接返回退款申请中状态
        // 实际项目中应查询数据库获取真实退款状态
        log.info("查询退款状态，用户ID: {}, 订单ID: {}", userId, orderId);
        return 0; // 申请中
    }
    
    @Override
    public int calculateMerchantMonthlySales(Long merchantId) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfMonth = now.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endOfMonth = now.withDayOfMonth(now.getMonth().length(now.toLocalDate().isLeapYear()))
                .withHour(23).withMinute(59).withSecond(59);

        // 通过订单项查询商家订单
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getMerchantId, merchantId)
                .between(OrderItem::getCreateTime, startOfMonth, endOfMonth)
        );

        // 获取这些订单项对应的订单ID
        List<Long> orderIds = orderItems.stream()
            .map(OrderItem::getOrderId)
            .distinct()
            .collect(Collectors.toList());

        // 查询这些订单中已完成的订单
        List<Order> completedOrders = list(
            new LambdaQueryWrapper<Order>()
                .in(Order::getId, orderIds)
                .eq(Order::getStatus, OrderStatus.COMPLETED.getCode())
        );

        // 计算总销售额
        return completedOrders.stream()
            .map(Order::getTotalAmount)
            .filter(Objects::nonNull)
            .mapToInt(BigDecimal::intValue)
            .sum();
    }

    @Override
    public int calculateMerchantTotalSales(Long merchantId) {
        // 通过订单项查询商家订单
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getMerchantId, merchantId)
        );

        // 获取这些订单项对应的订单ID
        List<Long> orderIds = orderItems.stream()
            .map(OrderItem::getOrderId)
            .distinct()
            .collect(Collectors.toList());

        // 查询这些订单中已完成的订单
        List<Order> completedOrders = list(
            new LambdaQueryWrapper<Order>()
                .in(Order::getId, orderIds)
                .eq(Order::getStatus, OrderStatus.COMPLETED.getCode())
        );

        // 计算总销售额
        return completedOrders.stream()
            .map(Order::getTotalAmount)
            .filter(Objects::nonNull)
            .mapToInt(BigDecimal::intValue)
            .sum();
    }

    @Override
    public List<Order> getUserRecentOrders(Long userId, int limit) {
        log.info("获取用户最近订单，用户ID: {}, 限制数量: {}", userId, limit);
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getUserId, userId)
                    .eq(Order::getStatus, OrderStatus.COMPLETED.getCode())
                    .orderByDesc(Order::getCreateTime)
                    .last("LIMIT " + limit);
            
            return list(queryWrapper);
        } catch (Exception e) {
            log.error("获取用户最近订单失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取用户优惠券
     * 实际项目中应该从数据库查询
     * @param userId 用户ID
     * @param couponId 优惠券ID
     * @return 用户优惠券
     */
    private UserCoupon getUserCoupon(Long userId, Long couponId) {
        return userCouponService.getUserCoupon(userId, couponId);
    }
    
    /**
     * 获取用户可用优惠券列表
     * 实际项目中应该从数据库查询
     * @param userId 用户ID
     * @param merchantId 商家ID
     * @param totalAmount 订单金额
     * @return 可用优惠券列表
     */
    public List<UserCoupon> getAvailableCoupons(Long userId, Long merchantId, BigDecimal totalAmount) {
        return userCouponService.getAvailableCoupons(userId, merchantId, totalAmount);
    }
    
    /**
     * 验证优惠券是否可用于当前订单
     * @param coupon 优惠券
     * @param totalAmount 订单金额
     * @param merchantId 商家ID
     * @return 是否可用
     */
    private boolean validateCoupon(Coupon coupon, BigDecimal totalAmount, Long merchantId) {
        // 检查最低消费
        if (coupon.getMinSpend() != null && totalAmount.compareTo(coupon.getMinSpend()) < 0) {
            return false;
        }
        
        // 检查商家限制
        if (coupon.getMerchantId() != null && !coupon.getMerchantId().equals(merchantId)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 计算优惠券折扣金额
     * @param coupon 优惠券
     * @param totalAmount 订单金额
     * @return 折扣金额
     */
    private BigDecimal calculateCouponDiscount(Coupon coupon, BigDecimal totalAmount) {
        BigDecimal discountAmount = BigDecimal.ZERO;
        
        switch (coupon.getType()) {
            case 0: // 满减券
                discountAmount = coupon.getValue();
                break;
            case 1: // 折扣券
                // 折扣值应该是0-1之间的小数，例如0.8表示8折
                discountAmount = totalAmount.multiply(BigDecimal.ONE.subtract(coupon.getValue()));
                break;
            case 2: // 无门槛券
                discountAmount = coupon.getValue();
                break;
            default:
                log.warn("未知优惠券类型: {}", coupon.getType());
        }
        
        // 确保折扣金额不超过订单总额
        if (discountAmount.compareTo(totalAmount) > 0) {
            discountAmount = totalAmount;
        }
        
        return discountAmount;
    }

    /**
     * 定时任务：自动取消超时未支付订单
     * 每5分钟执行一次
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void autoCloseTimeoutOrders() {
        log.info("开始执行订单超时自动取消定时任务");
        
        try {
            // 1. 查询超时的未支付订单
            // 假设订单支付超时时间为30分钟
            LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(30);
            
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getStatus, OrderStatus.PENDING_PAYMENT.getCode())
                       .lt(Order::getCreateTime, timeoutTime);
            
            List<Order> timeoutOrders = list(queryWrapper);
            
            log.info("找到 {} 个超时未支付订单", timeoutOrders.size());
            
            // 2. 批量取消订单
            for (Order order : timeoutOrders) {
                try {
                    // 设置订单状态为已取消
                    order.setStatus(OrderStatus.CANCELLED.getCode());
                    order.setCancelReason("超时未支付，系统自动取消");
                    order.setUpdateTime(LocalDateTime.now());
                    
                    boolean updated = updateById(order);
                    
                    if (updated) {
                        // 归还库存
                        List<OrderItem> orderItems = orderItemService.list(
                            new LambdaQueryWrapper<OrderItem>()
                                .eq(OrderItem::getOrderId, order.getId())
                        );
                        
                        for (OrderItem item : orderItems) {
                            Product product = productService.getById(item.getProductId());
                            if (product != null) {
                                product.setStock(product.getStock() + item.getQuantity());
                                productService.updateById(product);
                            }
                        }
                        
                        log.info("订单超时自动取消成功，订单ID: {}", order.getId());
                    } else {
                        log.error("订单超时自动取消失败，订单ID: {}", order.getId());
                    }
                } catch (Exception e) {
                    log.error("处理超时订单异常，订单ID: {}", order.getId(), e);
                }
            }
            
            log.info("订单超时自动取消定时任务执行完成");
        } catch (Exception e) {
            log.error("订单超时自动取消定时任务执行异常", e);
        }
    }
    
    /**
     * 手动触发订单超时检查
     * 用于测试或手动执行超时订单检查
     */
    public void manualCheckTimeoutOrders() {
        autoCloseTimeoutOrders();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean shipOrder(Long orderId, String deliveryCompany, String deliveryNo) {
        log.info("商家发货，订单ID: {}, 快递公司: {}, 快递单号: {}", orderId, deliveryCompany, deliveryNo);
        
        // 1. 获取订单
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 2. 校验订单状态
        if (order.getStatus() != OrderStatus.PENDING_SHIPMENT.getCode()) { // 1-待发货
            throw new BusinessException("订单状态不正确，无法发货");
        }
        
        // 3. 更新订单状态为已发货
        order.setStatus(OrderStatus.PENDING_RECEIPT.getCode()); // 2-待收货
        order.setDeliveryCompany(deliveryCompany);
        order.setDeliveryNo(deliveryNo);
        order.setDeliveryTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        // 4. 保存订单
        boolean updated = updateById(order);
        
        if (updated) {
            log.info("订单发货成功，订单ID: {}", orderId);
        } else {
            log.error("订单发货失败，订单ID: {}", orderId);
        }
        
        return updated;
    }
    
    @Override
    public IPage<OrderVO> getMerchantOrders(Page<Order> page, Long merchantId, Integer status) {
        log.info("获取商家订单列表，商家ID: {}, 状态: {}", merchantId, status);
        
        // 通过订单项查询商家订单
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getMerchantId, merchantId)
        );

        // 获取这些订单项对应的订单ID
        List<Long> orderIds = orderItems.stream()
            .map(OrderItem::getOrderId)
            .distinct()
            .collect(Collectors.toList());

        // 如果订单ID列表为空，直接返回空结果
        if (orderIds.isEmpty()) {
            IPage<OrderVO> emptyPage = new Page<>(page.getCurrent(), page.getSize(), 0);
            emptyPage.setRecords(new ArrayList<>());
            return emptyPage;
        }

        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Order::getId, orderIds);
        if (status != null) {
            queryWrapper.eq(Order::getStatus, status);
        }
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        // 查询订单分页数据
        IPage<Order> orderPage = page(page, queryWrapper);
        
        // 转换为OrderVO
        IPage<OrderVO> orderVOPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            
            // 设置订单状态文本
            switch (order.getStatus()) {
                case 0:
                    orderVO.setStatusText("待付款");
                    break;
                case 1:
                    orderVO.setStatusText("待发货");
                    break;
                case 2:
                    orderVO.setStatusText("待收货");
                    break;
                case 3:
                    orderVO.setStatusText("已完成");
                    break;
                case 4:
                    orderVO.setStatusText("已取消");
                    break;
                default:
                    orderVO.setStatusText("未知状态");
            }
            
            // 获取订单项
            List<OrderItem> merchantOrderItems = orderItemService.list(
                new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderId, order.getId())
                    .eq(OrderItem::getMerchantId, merchantId)
            );
            orderVO.setOrderItems(merchantOrderItems);
            
            // 计算商品总数
            int totalQuantity = 0;
            for (OrderItem item : merchantOrderItems) {
                totalQuantity += item.getQuantity();
            }
            orderVO.setTotalQuantity(totalQuantity);
            
            // 设置主商品图片
            if (!merchantOrderItems.isEmpty()) {
                orderVO.setMainProductImg(merchantOrderItems.get(0).getProductImg());
            }
            
            return orderVO;
        }).collect(Collectors.toList());
        
        orderVOPage.setRecords(orderVOList);
        return orderVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditRefund(Long merchantId, RefundAuditDTO refundAuditDTO) {
        // 1. 获取订单信息
        Order order = getById(refundAuditDTO.getOrderId());
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        // 2. 验证订单是否属于该商家
        if (!merchantId.equals(order.getUserId())) { // 假设订单的userId字段存储的是商家ID
            throw new BusinessException("无权操作此订单");
        }
        // 3. 验证订单状态是否为退款中
        // 这里可以根据实际业务调整
        // 4. 查询最新的退款单
        OrderRefund refund = orderRefundService.lambdaQuery()
            .eq(OrderRefund::getOrderId, refundAuditDTO.getOrderId())
            .orderByDesc(OrderRefund::getCreateTime)
            .last("limit 1")
            .one();
        if (refund == null) {
            throw new BusinessException("退款记录不存在");
        }
        // 5. 根据审核结果处理退款
        if (refundAuditDTO.getApproved()) {
            refund.setStatus(4); // 已完成
            refund.setRefundTime(LocalDateTime.now());
            order.setStatus(6); // 已退款
        } else {
            refund.setStatus(5); // 已拒绝
            refund.setRefuseReason(refundAuditDTO.getRemark());
            order.setStatus(1); // 恢复为已支付
        }
        refund.setUpdateTime(LocalDateTime.now());
        orderRefundService.updateById(refund);
        updateById(order);
        return true;
    }

    @Override
    public OrderDetailVO getMerchantOrderDetail(Long merchantId, Long orderId) {
        log.info("商家端获取订单详情，商家ID: {}, 订单ID: {}", merchantId, orderId);
        // 1. 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        // 2. 校验订单是否属于该商家（订单项中有该商家ID即可）
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId)
        );
        boolean belongToMerchant = orderItems.stream().anyMatch(item -> item.getMerchantId().equals(merchantId));
        if (!belongToMerchant) {
            throw new BusinessException("无权查看此订单");
        }

        OrderDetailVO detailVO = new OrderDetailVO();
        BeanUtils.copyProperties(order, detailVO);
        
        // 设置订单状态文本
        detailVO.setStatusText(getOrderStatusText(order.getStatus()));
        
        // 获取商家信息
        try {
            String shopName = getMerchantShopName(order.getMerchantId());
            if (shopName != null) {
                detailVO.setMerchantName(shopName);
            }
        } catch (Exception e) {
            log.warn("获取商家信息失败: merchantId={}", order.getMerchantId(), e);
        }
        
        // 获取用户信息
        try {
            UserInfoVO userInfo = userCenterService.getUserInfo(order.getUserId());
            if (userInfo != null) {
                detailVO.setUserName(userInfo.getNickname());
                detailVO.setUserPhone(userInfo.getPhone());
            }
        } catch (Exception e) {
            log.warn("获取用户信息失败: userId={}", order.getUserId(), e);
        }
        
        // 解析收货地址快照
        try {
            if (order.getAddressSnapshot() != null) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> addressMap = mapper.readValue(order.getAddressSnapshot(), Map.class);
                detailVO.setReceiverName(addressMap.get("receiverName"));
                detailVO.setReceiverPhone(addressMap.get("receiverPhone"));
                detailVO.setReceiverAddress(String.format("%s %s %s", 
                    addressMap.get("province"), 
                    addressMap.get("city"), 
                    addressMap.get("district")));
                detailVO.setReceiverDetailAddress(addressMap.get("detailAddress"));
            }
        } catch (Exception e) {
            log.warn("解析收货地址快照失败: orderId={}", orderId, e);
        }
        
        // 设置订单项（只返回该商家的订单项）
        List<OrderItem> merchantOrderItems = orderItems.stream()
            .filter(item -> item.getMerchantId().equals(merchantId))
            .collect(Collectors.toList());
        detailVO.setOrderItems(merchantOrderItems);
        
        // 计算商品总数
        int totalQuantity = merchantOrderItems.stream()
            .mapToInt(OrderItem::getQuantity)
            .sum();
        detailVO.setTotalQuantity(totalQuantity);
        
        // 设置主商品图片
        if (!merchantOrderItems.isEmpty()) {
            detailVO.setMainProductImg(merchantOrderItems.get(0).getProductImg());
        }
        
        // 设置按钮状态
        detailVO.setCanPay(false); // 商家端不需要支付按钮
        detailVO.setCanCancel(false); // 商家端不需要取消按钮
        detailVO.setCanConfirm(order.getStatus() == OrderStatus.PENDING_SHIPMENT.getCode()); // 待发货可发货
        detailVO.setCanRefund(order.getStatus() == OrderStatus.COMPLETED.getCode()); // 已完成可退款
        
        return detailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(Long orderId, Integer status) {
        try {
            // 更新订单状态
            Order order = getById(orderId);
            if (order == null) {
                log.warn("订单不存在: orderId={}", orderId);
                return false;
            }

            order.setStatus(status);
            order.setUpdateTime(LocalDateTime.now());
            boolean updated = updateById(order);

            if (updated) {
                // 发送业务消息
                try {
                    BusinessMessageDTO messageDTO = BusinessMessageDTO.builder()
                        .type(getMessageType(status))
                        .businessId(orderId)
                        .userId(order.getUserId())
                        .params(buildMessageParams(order))
                        .build();
                        
                    businessMessageService.sendBusinessMessage(messageDTO);
                } catch (Exception e) {
                    log.error("发送订单状态变更消息失败: orderId={}, status={}, error={}", 
                        orderId, status, e.getMessage(), e);
                }
            }

            return updated;
        } catch (Exception e) {
            log.error("更新订单状态失败: orderId={}, status={}, error={}", 
                orderId, status, e.getMessage(), e);
            throw e;
        }
    }

    private BusinessMessageType getMessageType(Integer status) {
        switch (status) {
            case 1: return BusinessMessageType.ORDER_PAID;
            case 2: return BusinessMessageType.ORDER_SHIPPED;
            case 3: return BusinessMessageType.ORDER_COMPLETED;
            case 4: return BusinessMessageType.ORDER_COMPLETED;
            case 5: return BusinessMessageType.ORDER_CANCELLED;
            default: return BusinessMessageType.ORDER_CREATED;
        }
    }

    private Map<String, Object> buildMessageParams(Order order) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", order.getOrderNo());
        params.put("amount", order.getTotalAmount());
        params.put("status", order.getStatus());
        return params;
    }

    private void publishOrderEvent(OrderEvent event) {
        eventPublisher.publishEvent(event);
    }

    @Override
    public IPage<OrderVO> getOrderVOPage(Page<Order> page, LambdaQueryWrapper<Order> wrapper) {
        // 执行分页查询
        IPage<Order> orderPage = page(page, wrapper);
        
        // 转换为OrderVO
        IPage<OrderVO> orderVOPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            
            // 设置订单状态文本
            orderVO.setStatusText(getOrderStatusText(order.getStatus()));
            
            // 获取订单项
            List<OrderItem> orderItems = orderItemService.list(
                new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderId, order.getId())
            );
            orderVO.setOrderItems(orderItems);
            
            // 计算商品总数
            int totalQuantity = orderItems.stream()
                .mapToInt(OrderItem::getQuantity)
                .sum();
            orderVO.setTotalQuantity(totalQuantity);
            
            return orderVO;
        }).collect(Collectors.toList());
        
        orderVOPage.setRecords(orderVOList);
        return orderVOPage;
    }

    @Override
    public OrderDetailVO getAdminOrderDetail(Long id) {
        // 获取订单信息
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        OrderDetailVO detailVO = new OrderDetailVO();
        BeanUtils.copyProperties(order, detailVO);
        
        // 设置订单状态文本
        detailVO.setStatusText(getOrderStatusText(order.getStatus()));
        
        // 获取商家信息
        try {
            String shopName = getMerchantShopName(order.getMerchantId());
            if (shopName != null) {
                detailVO.setMerchantName(shopName);
            }
        } catch (Exception e) {
            log.warn("获取商家信息失败: merchantId={}", order.getMerchantId(), e);
        }
        
        // 获取用户信息
        try {
            UserInfoVO userInfo = userCenterService.getUserInfo(order.getUserId());
            if (userInfo != null) {
                detailVO.setUserName(userInfo.getNickname());
                detailVO.setUserPhone(userInfo.getPhone());
            }
        } catch (Exception e) {
            log.warn("获取用户信息失败: userId={}", order.getUserId(), e);
        }
        
        // 解析收货地址快照
        try {
            if (order.getAddressSnapshot() != null) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> addressMap = mapper.readValue(order.getAddressSnapshot(), Map.class);
                detailVO.setReceiverName(addressMap.get("receiverName"));
                detailVO.setReceiverPhone(addressMap.get("receiverPhone"));
                detailVO.setReceiverAddress(String.format("%s %s %s", 
                    addressMap.get("province"), 
                    addressMap.get("city"), 
                    addressMap.get("district")));
                detailVO.setReceiverDetailAddress(addressMap.get("detailAddress"));
            }
        } catch (Exception e) {
            log.warn("解析收货地址快照失败: orderId={}", id, e);
        }
        
        // 获取订单项
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, id)
        );
        detailVO.setOrderItems(orderItems);
        
        // 计算商品总数
        int totalQuantity = orderItems.stream()
            .mapToInt(OrderItem::getQuantity)
            .sum();
        detailVO.setTotalQuantity(totalQuantity);
        
        // 设置按钮状态（管理员可以进行所有操作）
        detailVO.setCanPay(false); // 管理员不需要支付按钮
        detailVO.setCanCancel(order.getStatus() != OrderStatus.CANCELLED.getCode() 
            && order.getStatus() != OrderStatus.COMPLETED.getCode()); // 非取消和完成状态可取消
        detailVO.setCanConfirm(false); // 管理员不需要确认收货按钮
        detailVO.setCanRefund(order.getStatus() != OrderStatus.PENDING_PAYMENT.getCode() 
            && order.getStatus() != OrderStatus.CANCELLED.getCode()); // 非待付款和已取消可退款
        
        return detailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean forceRefund(Long id, String reason) {
        // 获取订单信息
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 验证订单状态
        if (order.getStatus() == OrderStatus.CANCELLED.getCode() || 
            order.getStatus() == OrderStatus.PENDING_PAYMENT.getCode()) {
            throw new BusinessException("当前订单状态不能退款");
        }

        try {
            // 创建退款记录
            OrderRefund refund = new OrderRefund();
            refund.setOrderId(id);
            refund.setUserId(order.getUserId());
            refund.setRefundNo(generateRefundNo());
            refund.setRefundAmount(order.getPayAmount());
            refund.setRefundReason("管理员强制退款：" + reason);
            refund.setRefundType(0); // 仅退款
            refund.setStatus(4); // 已完成
            refund.setCreateTime(LocalDateTime.now());
            refund.setUpdateTime(LocalDateTime.now());
            refund.setRefundTime(LocalDateTime.now());
            orderRefundService.save(refund);

            // 更新订单状态
            order.setStatus(6); // 已退款
            order.setUpdateTime(LocalDateTime.now());
            updateById(order);

            // 发送消息通知
            try {
                BusinessMessageDTO messageDTO = BusinessMessageDTO.builder()
                    .type(BusinessMessageType.ORDER_REFUND)
                    .businessId(id)
                    .userId(order.getUserId())
                    .params(buildMessageParams(order))
                    .build();
                
                businessMessageService.sendBusinessMessage(messageDTO);
            } catch (Exception e) {
                log.error("发送退款通知失败: orderId={}, error={}", id, e.getMessage(), e);
            }

            log.info("管理员强制退款成功，订单ID: {}, 原因: {}", id, reason);
            return true;
        } catch (Exception e) {
            log.error("管理员强制退款失败，订单ID: {}", id, e);
            throw new BusinessException("退款失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean forceCancel(Long id, String reason) {
        // 获取订单信息
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 验证订单状态
        if (order.getStatus() == OrderStatus.CANCELLED.getCode() || 
            order.getStatus() == OrderStatus.COMPLETED.getCode()) {
            throw new BusinessException("当前订单状态不能取消");
        }

        try {
            // 更新订单状态
            order.setStatus(OrderStatus.CANCELLED.getCode());
            order.setCancelReason("管理员强制取消：" + reason);
            order.setUpdateTime(LocalDateTime.now());
            updateById(order);

            // 如果订单已支付，创建退款记录
            if (order.getPaymentTime() != null) {
                OrderRefund refund = new OrderRefund();
                refund.setOrderId(id);
                refund.setUserId(order.getUserId());
                refund.setRefundNo(generateRefundNo());
                refund.setRefundAmount(order.getPayAmount());
                refund.setRefundReason("管理员强制取消订单：" + reason);
                refund.setRefundType(0); // 仅退款
                refund.setStatus(4); // 已完成
                refund.setCreateTime(LocalDateTime.now());
                refund.setUpdateTime(LocalDateTime.now());
                refund.setRefundTime(LocalDateTime.now());
                orderRefundService.save(refund);
            }

            // 归还库存
            List<OrderItem> orderItems = orderItemService.list(
                new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderId, id)
            );
            
            for (OrderItem item : orderItems) {
                if (item.getSkuId() != null && item.getSkuId() > 0) {
                    ProductSku sku = productSkuService.getById(item.getSkuId());
                    if (sku != null) {
                        sku.setStock(sku.getStock() + item.getQuantity());
                        productSkuService.updateById(sku);
                    }
                } else {
                    Product product = productService.getById(item.getProductId());
                    if (product != null) {
                        product.setStock(product.getStock() + item.getQuantity());
                        productService.updateById(product);
                    }
                }
            }

            // 发送消息通知
            try {
                BusinessMessageDTO messageDTO = BusinessMessageDTO.builder()
                    .type(BusinessMessageType.ORDER_CANCELLED)
                    .businessId(id)
                    .userId(order.getUserId())
                    .params(buildMessageParams(order))
                    .build();
                
                businessMessageService.sendBusinessMessage(messageDTO);
            } catch (Exception e) {
                log.error("发送订单取消通知失败: orderId={}, error={}", id, e.getMessage(), e);
            }

            log.info("管理员强制取消订单成功，订单ID: {}, 原因: {}", id, reason);
            return true;
        } catch (Exception e) {
            log.error("管理员强制取消订单失败，订单ID: {}", id, e);
            throw new BusinessException("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 获取订单状态文本
     */
    private String getOrderStatusText(Integer status) {
        switch (status) {
            case 0:
                return "待付款";
            case 1:
                return "待发货";
            case 2:
                return "待收货";
            case 3:
                return "已完成";
            case 4:
                return "已取消";
            case 5:
                return "退款中";
            case 6:
                return "已退款";
            default:
                return "未知状态";
        }
    }

    /**
     * 获取商家店铺名称
     * @param merchantId 商家ID
     * @return 店铺名称
     */
    private String getMerchantShopName(Long merchantId) {
        return orderMapper.getMerchantShopName(merchantId);
    }

    @Override
    public boolean isProductInOrder(Long orderId, Long productId) {
        // 通过OrderItemService查询订单项
        List<OrderItem> orderItems = orderItemService.list(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId)
                .eq(OrderItem::getProductId, productId)
        );
        return !orderItems.isEmpty();
    }
} 